#!/usr/bin/env python
#encoding:utf8

import sys,cPickle,time,commands
import api,init

k = init.INIT()
hostlist = k.getClientList()
contact = k.contact
workdir = k.WorkDir
interval = k.notifyinterval
notify = k.notify

saveout = sys.stdout
fsock = open('%s/logs/notifymail.log' % workdir,'a')
sys.stdout = fsock
sys.stderr = fsock

nowtime = time.strftime('%Y-%m-%d %H:%M:%S')

try:
    with open('/tmp/monitor-daemon.txt','r') as f:
        alldata = cPickle.load(f)
except:
    print '%s %s get params open /tmp/monitor-daemon.txt error.' % (nowtime,__file__)

def sendmail(subject,context):
    fromaddr = 'monitor@localhost.localdomain'
    print '%s %s sendmail %s' % (nowtime,__file__,subject)
    command = "python %s/bin/sendmail -f %s -t %s -s \'%s\' -c \"%s\"" % (workdir,fromaddr,contact,subject,context)
    status,output = commands.getstatusoutput(command)
    print output

def addhost(host):
    global result
    result[host] = {}
    for project in alldata[host]:
        if project == 'get_time':continue
        result[host][project] = {}
        if alldata[host][project]['status'] == 'Ok':
            result[host][project]['value'] = 0
            result[host][project]['notify'] = 0
        else:
            result[host][project]['value'] = 1
            result[host][project]['notify'] = 0

def isOk():
    global result
    if result[host][project]['value'] >= 3:
        subject = "%s %s recover" % (host,project)
        context = '''时间：%s\n节点：%s\n运行服务：%s\n检测项目：%s\n检测信息：%s\n''' % (time.strftime('%Y-%m-%d %H:%M:%S'),host,k.getClientHavProject(host),project,alldata[host][project]['info'])
        sendmail(subject,context)
    result[host][project]['value'] = 0
    result[host][project]['notify'] = 0

def isBad():
    global result
    try:
        result[host][project]['value'] += 1
    except KeyError:
        result[host][project] = {'value':0,'notify':0}
    print 'Check %s of %s problem time：%s' % (host,project,result[host][project]['value'])
    if result[host][project]['value'] >= 3:
        if time.time() - result[host][project]['notify'] >= result['interval']:
            subject = "%s %s problem" % (host,project)
            context = '''时间：%s\n节点：%s\n运行服务：%s\n检测项目：%s\n检测信息：%s\n''' % (time.strftime('%Y-%m-%d %H:%M:%S'),host,k.getClientHavProject(host),project,alldata[host][project]['info'])
            sendmail(subject,context)
            result[host][project]['notify'] = time.time()
            return 'send'


if notify != 'true':
    print '%s %s notify is disabled.' % (nowtime,__file__)
    sys.exit()

# no file 
try:
    with open('/tmp/monitor-mail.txt','r') as f:
        result = cPickle.load(f)
except:
    result = {}
    for host in hostlist:
        result[host] = {}
        addhost(host)
    with open('/tmp/monitor-mail.txt','w') as f:
        cPickle.dump(result,f)
    sys.exit()
# start 
result['interval'] = int(interval)
monitoralias = {}

for monitor in k.getMonitorList():
    monitoralias[monitor] = k.getMonitorAtt(monitor)

for host in hostlist:
    if not result.get(host,''):
        addhost(host)
        continue
    for delproject in [ val for val in result[host] if val not in alldata[host] ]:
        print 'Clear %s for %s info.' % (host,delproject)
        del result[host][delproject]
    for addproject in [ val for val in alldata[host] if val not in result[host] ]:
        if addproject == 'get_time':continue
        print 'Add %s for %s info.' % (host,addproject)
        result[host][addproject] = {'value':0,'notify':0}
    try:
        if alldata[host]['check_ping']['status'] == 'Bad':
            project = 'check_ping'
            if isBad():continue
        else:
            project = 'check_ping'
            isOk()
    except:
        pass
    for project in alldata[host]:
        if project == 'check_ping' or project == 'get_time':continue
        if alldata[host][project]['status'] == 'Ok':
            isOk()
        else:
            isBad()
with open('/tmp/monitor-mail.txt','w') as f:
    cPickle.dump(result,f)
print '%s %s completed check.' % (nowtime,__file__)
sys.stdout = saveout
fsock.close()
